from PySide6.QtWidgets import (QDialog, QVBoxLayout, QHBoxLayout, QLabel, 
                              QPushButton, QGroupBox, QGridLayout, QProgressBar,
                              QTextEdit, QTabWidget, QWidget)
from PySide6.QtCore import Qt, QTimer, Signal
from PySide6.QtGui import QFont
import time
import threading

class PerformanceMonitorDialog(QDialog):
    """性能监控对话框 - 实时显示程序性能指标"""
    
    def __init__(self, main_window, parent=None):
        super().__init__(parent)
        self.main_window = main_window
        self.setWindowTitle("性能监控")
        self.setFixedSize(600, 500)
        self.monitoring = False
        self.setup_ui()
        
        # 更新定时器
        self.update_timer = QTimer()
        self.update_timer.timeout.connect(self.update_stats)
        
    def setup_ui(self):
        layout = QVBoxLayout(self)
        
        # 标题
        title_label = QLabel("实时性能监控")
        title_font = QFont()
        title_font.setPointSize(14)
        title_font.setBold(True)
        title_label.setFont(title_font)
        title_label.setAlignment(Qt.AlignCenter)
        layout.addWidget(title_label)
        
        # 创建选项卡
        tab_widget = QTabWidget()
        layout.addWidget(tab_widget)
        
        # 基础性能页
        basic_tab = QWidget()
        tab_widget.addTab(basic_tab, "基础性能")
        self.setup_basic_tab(basic_tab)
        
        # 检测性能页
        detection_tab = QWidget()
        tab_widget.addTab(detection_tab, "检测性能")
        self.setup_detection_tab(detection_tab)
        
        # 系统资源页
        system_tab = QWidget()
        tab_widget.addTab(system_tab, "系统资源")
        self.setup_system_tab(system_tab)
        
        # 控制按钮
        button_layout = QHBoxLayout()
        self.start_btn = QPushButton("开始监控")
        self.start_btn.clicked.connect(self.toggle_monitoring)
        button_layout.addWidget(self.start_btn)
        
        self.clear_btn = QPushButton("清除数据")
        self.clear_btn.clicked.connect(self.clear_data)
        button_layout.addWidget(self.clear_btn)
        
        button_layout.addStretch()
        
        self.close_btn = QPushButton("关闭")
        self.close_btn.clicked.connect(self.close)
        button_layout.addWidget(self.close_btn)
        
        layout.addLayout(button_layout)
        
    def setup_basic_tab(self, tab):
        layout = QGridLayout(tab)
        
        # 检测状态组
        status_group = QGroupBox("检测状态")
        status_layout = QGridLayout(status_group)
        
        status_layout.addWidget(QLabel("检测线程状态:"), 0, 0)
        self.thread_status_label = QLabel("未知")
        status_layout.addWidget(self.thread_status_label, 0, 1)
        
        status_layout.addWidget(QLabel("活跃触发器:"), 1, 0)
        self.active_triggers_label = QLabel("0")
        status_layout.addWidget(self.active_triggers_label, 1, 1)
        
        status_layout.addWidget(QLabel("检测间隔:"), 2, 0)
        self.detection_interval_label = QLabel("0.1s")
        status_layout.addWidget(self.detection_interval_label, 2, 1)
        
        layout.addWidget(status_group, 0, 0, 1, 2)
        
        # 性能指标组
        perf_group = QGroupBox("性能指标")
        perf_layout = QGridLayout(perf_group)
        
        perf_layout.addWidget(QLabel("平均检测时间:"), 0, 0)
        self.avg_detection_time_label = QLabel("0ms")
        perf_layout.addWidget(self.avg_detection_time_label, 0, 1)
        
        perf_layout.addWidget(QLabel("检测频率:"), 1, 0)
        self.detection_freq_label = QLabel("0 Hz")
        perf_layout.addWidget(self.detection_freq_label, 1, 1)
        
        layout.addWidget(perf_group, 1, 0, 1, 2)
        
    def setup_detection_tab(self, tab):
        layout = QVBoxLayout(tab)
        
        # 检测统计
        stats_group = QGroupBox("检测统计")
        stats_layout = QGridLayout(stats_group)
        
        stats_layout.addWidget(QLabel("总检测次数:"), 0, 0)
        self.total_detections_label = QLabel("0")
        stats_layout.addWidget(self.total_detections_label, 0, 1)
        
        stats_layout.addWidget(QLabel("颜色匹配次数:"), 1, 0)
        self.color_matches_label = QLabel("0")
        stats_layout.addWidget(self.color_matches_label, 1, 1)
        
        stats_layout.addWidget(QLabel("触发执行次数:"), 2, 0)
        self.trigger_executions_label = QLabel("0")
        stats_layout.addWidget(self.trigger_executions_label, 2, 1)
        
        layout.addWidget(stats_group)
        
        # 性能趋势
        trend_group = QGroupBox("性能趋势")
        trend_layout = QVBoxLayout(trend_group)
        
        self.performance_log = QTextEdit()
        self.performance_log.setMaximumHeight(200)
        self.performance_log.setReadOnly(True)
        trend_layout.addWidget(self.performance_log)
        
        layout.addWidget(trend_group)
        
    def setup_system_tab(self, tab):
        layout = QVBoxLayout(tab)
        
        # 内存使用
        memory_group = QGroupBox("内存使用")
        memory_layout = QGridLayout(memory_group)
        
        memory_layout.addWidget(QLabel("程序内存:"), 0, 0)
        self.memory_usage_label = QLabel("0 MB")
        memory_layout.addWidget(self.memory_usage_label, 0, 1)
        
        self.memory_progress = QProgressBar()
        self.memory_progress.setRange(0, 100)
        memory_layout.addWidget(self.memory_progress, 1, 0, 1, 2)
        
        layout.addWidget(memory_group)
        
        # CPU使用
        cpu_group = QGroupBox("CPU使用")
        cpu_layout = QGridLayout(cpu_group)
        
        cpu_layout.addWidget(QLabel("CPU使用率:"), 0, 0)
        self.cpu_usage_label = QLabel("0%")
        cpu_layout.addWidget(self.cpu_usage_label, 0, 1)
        
        self.cpu_progress = QProgressBar()
        self.cpu_progress.setRange(0, 100)
        cpu_layout.addWidget(self.cpu_progress, 1, 0, 1, 2)
        
        layout.addWidget(cpu_group)
        
        # 线程信息
        thread_group = QGroupBox("线程信息")
        thread_layout = QGridLayout(thread_group)
        
        thread_layout.addWidget(QLabel("活跃线程数:"), 0, 0)
        self.thread_count_label = QLabel("0")
        thread_layout.addWidget(self.thread_count_label, 0, 1)
        
        layout.addWidget(thread_group)
        
    def toggle_monitoring(self):
        """切换监控状态"""
        if self.monitoring:
            self.stop_monitoring()
        else:
            self.start_monitoring()
            
    def start_monitoring(self):
        """开始监控"""
        self.monitoring = True
        self.start_btn.setText("停止监控")
        self.update_timer.start(1000)  # 每秒更新
        self.log_message("开始性能监控")
        
    def stop_monitoring(self):
        """停止监控"""
        self.monitoring = False
        self.start_btn.setText("开始监控")
        self.update_timer.stop()
        self.log_message("停止性能监控")
        
    def update_stats(self):
        """更新统计信息"""
        try:
            if hasattr(self.main_window, 'get_performance_stats'):
                stats = self.main_window.get_performance_stats()
                
                # 更新基础性能
                self.thread_status_label.setText("运行中" if stats.get('detection_running', False) else "已停止")
                self.active_triggers_label.setText(str(stats.get('active_triggers', 0)))
                
                if hasattr(self.main_window, 'detection_interval'):
                    self.detection_interval_label.setText(f"{self.main_window.detection_interval:.3f}s")
                
                if hasattr(self.main_window, 'performance_stats'):
                    perf_stats = self.main_window.performance_stats
                    avg_time = perf_stats.get('avg_detection_time', 0) * 1000
                    self.avg_detection_time_label.setText(f"{avg_time:.1f}ms")
                    
                    freq = 1.0 / max(0.001, perf_stats.get('avg_detection_time', 0.1))
                    self.detection_freq_label.setText(f"{freq:.1f} Hz")
                
                # 更新系统资源
                self.update_system_resources()
                
        except Exception as e:
            self.log_message(f"更新统计信息失败: {e}")
            
    def update_system_resources(self):
        """更新系统资源信息"""
        try:
            import psutil
            import os
            
            # 获取当前进程
            process = psutil.Process(os.getpid())
            
            # 内存使用
            memory_info = process.memory_info()
            memory_mb = memory_info.rss / 1024 / 1024
            self.memory_usage_label.setText(f"{memory_mb:.1f} MB")
            
            # CPU使用率
            cpu_percent = process.cpu_percent()
            self.cpu_usage_label.setText(f"{cpu_percent:.1f}%")
            self.cpu_progress.setValue(int(cpu_percent))
            
            # 线程数
            thread_count = process.num_threads()
            self.thread_count_label.setText(str(thread_count))
            
        except ImportError:
            self.memory_usage_label.setText("需要安装 psutil")
        except Exception as e:
            self.log_message(f"获取系统资源失败: {e}")
            
    def log_message(self, message):
        """记录日志消息"""
        timestamp = time.strftime("%H:%M:%S")
        self.performance_log.append(f"[{timestamp}] {message}")
        
    def clear_data(self):
        """清除数据"""
        self.performance_log.clear()
        self.log_message("数据已清除")
        
    def closeEvent(self, event):
        """关闭时停止监控"""
        if self.monitoring:
            self.stop_monitoring()
        super().closeEvent(event)
